#!/bin/bash
set -e

### 0. 基础变量
DISK="/dev/sda"
EFI_PART="${DISK}1"
ROOT_PART="${DISK}2"
MOUNTPOINT="/mnt"

### 1. 基础检查
echo "=== 检查磁盘和分区 ==="

# 检查目标磁盘是否存在
if [ ! -b "$DISK" ]; then
    echo "错误：磁盘 $DISK 不存在！"
    echo "请检查脚本中的 DISK 变量设置。"
    exit 1
fi

# 检查EFI分区是否存在
if [ ! -b "$EFI_PART" ]; then
    echo "错误：EFI分区 $EFI_PART 不存在！"
    echo "请先对磁盘进行分区。"
    exit 1
fi

# 检查根分区是否存在
if [ ! -b "$ROOT_PART" ]; then
    echo "错误：根分区 $ROOT_PART 不存在！"
    echo "请先对磁盘进行分区。"
    exit 1
fi

echo "✓ 磁盘检查通过：$DISK"
echo "✓ EFI分区：$EFI_PART"
echo "✓ 根分区：$ROOT_PART"

### 2. 检查并卸载已挂载的分区
echo "=== 检查挂载状态 ==="

# 检查并卸载EFI分区
if mountpoint -q "$EFI_PART" 2>/dev/null || findmnt -n "$EFI_PART" >/dev/null 2>&1; then
    echo "检测到EFI分区已挂载，正在卸载..."
    umount -l "$EFI_PART" 2>/dev/null || umount "$EFI_PART" 2>/dev/null || true
fi

# 检查并卸载根分区
if mountpoint -q "$ROOT_PART" 2>/dev/null || findmnt -n "$ROOT_PART" >/dev/null 2>&1; then
    echo "检测到根分区已挂载，正在卸载..."
    umount -l "$ROOT_PART" 2>/dev/null || umount "$ROOT_PART" 2>/dev/null || true
fi

# 检查并卸载挂载点
if mountpoint -q "$MOUNTPOINT" 2>/dev/null; then
    echo "检测到挂载点 $MOUNTPOINT 已挂载，正在卸载..."
    umount -l "$MOUNTPOINT" 2>/dev/null || umount -R "$MOUNTPOINT" 2>/dev/null || true
fi

echo "=== 格式化分区 ==="
mkfs.fat -F32 $EFI_PART
mkfs.btrfs -f $ROOT_PART

echo "=== 创建 Btrfs 子卷 ==="
mount $ROOT_PART $MOUNTPOINT

# 创建标准的 Arch Linux 子卷结构
btrfs subvolume create $MOUNTPOINT/@
btrfs subvolume create $MOUNTPOINT/@home
btrfs subvolume create $MOUNTPOINT/@var_log
btrfs subvolume create $MOUNTPOINT/@var_cache
btrfs subvolume create $MOUNTPOINT/@snapshots

# 设置快照子卷为只读（推荐做法）
btrfs property set $MOUNTPOINT/@snapshots ro true

umount $MOUNTPOINT

echo "=== 挂载子卷 ==="
# 挂载根子卷
mount -o subvol=@,compress=zstd:3,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT

# 创建挂载点目录
mkdir -p $MOUNTPOINT/{boot/efi,home,var/log,var/cache,.snapshots}

# 挂载其他子卷
mount -o subvol=@home,compress=zstd:3,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/home
mount -o subvol=@var_log,compress=zstd:3,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/var/log
mount -o subvol=@var_cache,compress=zstd:3,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/var/cache
mount -o subvol=@snapshots,compress=zstd:3,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/.snapshots

mount $EFI_PART $MOUNTPOINT/boot/efi

### 3. 配置 Pacman 镜像源
echo "=== 配置 Pacman 镜像源 ==="

# 备份原始镜像源文件
cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
echo "✓ 已备份原始镜像源文件"

# 将中科大镜像源添加到文件顶部
sed -i '1i\## 中国科学技术大学镜像源\nServer = https://mirrors.ustc.edu.cn/archlinux/$repo/os/$arch\n' /etc/pacman.d/mirrorlist
echo "✓ 已添加中科大镜像源"

# 可选：清理软件包缓存并更新数据库
pacman -Syy --noconfirm
echo "✓ 已更新软件包数据库"

echo "=== 安装基本系统 ==="
pacstrap $MOUNTPOINT base linux linux-firmware btrfs-progs snapper vim networkmanager sudo git

echo "=== 生成 fstab ==="
genfstab -U $MOUNTPOINT >> $MOUNTPOINT/etc/fstab

arch-chroot $MOUNTPOINT /bin/bash <<'EOF'
set -e

echo "=== 配置 Snapper ==="

# 由于 .snapshots 子卷已存在，手动创建配置文件
mkdir -p /etc/snapper/configs

# 创建 snapper root 配置
cat > /etc/snapper/configs/root << 'CONFIG'
# Snapper 配置文件 for Arch Linux with Btrfs
SUBVOLUME="/"
FSTYPE="btrfs"
ALLOW_USERS=""
ALLOW_GROUPS=""
SYNC_ACL="no"
TIMELINE_CREATE="yes"
TIMELINE_CLEANUP="yes"
TIMELINE_MIN_AGE="1800"
TIMELINE_LIMIT_HOURLY="10"
TIMELINE_LIMIT_DAILY="7"
TIMELINE_LIMIT_WEEKLY="4"
TIMELINE_LIMIT_MONTHLY="3"
BACKGROUND_COMPARISON="yes"
USE_SNAPPER="yes"
USE_BTRFS="yes"
NUMBER_CLEANUP="yes"
NUMBER_MIN_AGE="1800"
NUMBER_LIMIT="2-10"
NUMBER_LIMIT_IMPORTANT="4-10"
EMPTY_PRE_POST_CLEANUP="yes"
EMPTY_PRE_POST_MIN_AGE="1800"
EMPTY_PRE_POST_LIMIT="3-5"
CONFIG

# 验证配置文件是否创建成功
if [ ! -f "/etc/snapper/configs/root" ]; then
    echo "错误：Snapper 配置文件创建失败！"
    exit 1
fi

# 启用并启动 snapper 服务
systemctl enable snapper-timeline.timer
systemctl enable snapper-cleanup.timer

echo "=== 配置 pacman hooks 自动快照 ==="
mkdir -p /etc/pacman.d/hooks

# 创建 pacman 操作前快照钩子
cat > /etc/pacman.d/hooks/50-snapper-pre.hook << 'HOOK'
[Trigger]
Operation = Upgrade
Operation = Install
Operation = Remove
Type = Package
Target = *

[Action]
Description = 创建 pacman 操作前快照
When = PreTransaction
Exec = /usr/bin/snapper -c root create --description "pacman-pre" --cleanup-algorithm=number
HOOK

# 创建 pacman 操作后快照钩子
cat > /etc/pacman.d/hooks/50-snapper-post.hook << 'HOOK'
[Trigger]
Operation = Upgrade
Operation = Install
Operation = Remove
Type = Package
Target = *

[Action]
Description = 创建 pacman 操作后快照
When = PostTransaction
Exec = /usr/bin/snapper -c root create --description "pacman-post" --cleanup-algorithm=number
HOOK

# 创建验证脚本
cat > /usr/local/bin/snapper-check << 'CHECK'
#!/bin/bash
echo "=== Snapper 配置验证 ==="
if snapper list >/dev/null 2>&1; then
    echo "✓ Snapper 配置正常"
    snapper list
else
    echo "✗ Snapper 配置异常，请检查配置"
    exit 1
fi
CHECK

chmod +x /usr/local/bin/snapper-check

echo "=== 创建初始快照 ==="
if snapper create --description "系统安装完成" --cleanup-algorithm=number; then
    echo "✓ 初始快照创建成功"
else
    echo "⚠ 初始快照创建失败，请手动检查"
fi

EOF

# 验证 chroot 环境中的配置是否成功
echo "=== 验证 Snapper 配置 ==="
if arch-chroot $MOUNTPOINT snapper list >/dev/null 2>&1; then
    echo "✓ Snapper 配置验证成功"
    arch-chroot $MOUNTPOINT snapper list
else
    echo "⚠ Snapper 配置验证失败，请手动检查配置"
    echo "可运行以下命令进行故障排除："
    echo "arch-chroot $MOUNTPOINT /usr/local/bin/snapper-check"
fi

echo "=== 安装后验证和故障排除 ==="

# 验证 fstab 是否正确生成
if [ -f "$MOUNTPOINT/etc/fstab" ]; then
    echo "✓ fstab 文件已生成"
    echo "fstab 内容预览："
    echo "---"
    cat "$MOUNTPOINT/etc/fstab" | grep -E "^UUID|^subvol"
    echo "---"
else
    echo "✗ fstab 文件生成失败！"
    exit 1
fi

# 验证 Btrfs 子卷是否正确创建
echo "=== 验证 Btrfs 子卷 ==="
arch-chroot $MOUNTPOINT btrfs subvolume list / | grep -E "(@|@home|@var_log|@var_cache|@snapshots)" || {
    echo "⚠ 部分子卷可能未正确创建"
}

# 验证挂载状态
echo "=== 验证挂载状态 ==="
arch-chroot $MOUNTPOINT findmnt -n | grep -E "(btrfs|vfat)" || {
    echo "⚠ 部分分区可能未正确挂载"
}

echo ""
echo "=== 基础系统安装完成！==="
echo ""
echo "接下来需要手动完成以下配置："
echo "1. 进入系统：arch-chroot /mnt"
echo "2. 配置 bootloader (systemd-boot 或 GRUB)"
echo "3. 设置时区、语言环境、主机名"
echo "4. 设置 root 密码和创建用户"
echo "5. 启用网络服务：systemctl enable NetworkManager"
echo "6. 重启系统"
echo ""
echo "脚本已自动配置："
echo "✓ Btrfs 子卷结构（@, @home, @var_log, @var_cache, @snapshots）"
echo "✓ Snapper 快照系统（包含自动快照和清理）"
echo "✓ Pacman 自动快照钩子"
echo "✓ 基础系统软件包"
echo "✓ 网络管理器"
echo "✓ 文本编辑器 vim"
echo ""
echo "=== Snapper 使用说明 ==="
echo "进入系统后可以使用以下命令："
echo "- 查看快照列表：snapper list"
echo "- 创建手动快照：snapper create --description \"描述\""
echo "- 回滚快照：snapper rollback <number>"
echo "- 验证配置：/usr/local/bin/snapper-check"
echo ""
echo "=== 故障排除 ==="
echo "如果 Snapper 无法工作，请运行："
echo "arch-chroot /mnt /usr/local/bin/snapper-check"
echo "或手动检查配置文件：/etc/snapper/configs/root"
